import axios from 'axios'
import token from './token.ts'
import {ElMessage} from "element-plus"
import {eventBus} from "../index.ts"

let request: any

/**
 * 创建请求类
 */
const initRequest: any = (proxyUrl: string) => {
    request = axios.create({
        baseURL: proxyUrl,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        timeout: 20000,
        otherParams: {
            isLoading: false
        }
    })

    request.interceptors.request.use((config: any) => {
        if (config.otherParams) {
            if (config.otherParams.isLoading) {
                eventBus.emit("handleStartLoading")
            }
        }
        config.headers['Authorization'] = 'Bearer ' + token.get()
        return config
    }, (error: any) => {
        return Promise.reject(error)
    })

    /**
     * 响应拦截器
     */
    request.interceptors.response.use((res: any) => {
        return res.data.data
    }, (error: any) => {
        eventBus.emit("handleEndLoading")
        if (error.response) {
            if (error.response.status == 404) {
                ElMessage.error(`错误代码：${error.response.status}；错误信息：找不到接口！`)
            } else if (error.response.status == 401) {
                ElMessage.error(`错误代码：${error.response.status}；错误信息：身份验证失败，请重新登录！`)
                token.remove()
                setTimeout(() => {
                    location.reload()
                }, 1500)
            } else if (error.response.status == 400) {
                ElMessage.error(`错误代码：${error.response.data.status}；错误信息：${error.response.data.message}！`)
            } else {
                ElMessage.error(`错误代码：500；错误信息：未知错误，请联系管理员！`)
            }
        }
        return Promise.reject(error)
    })
}

/**
 * 暴露
 */
export {
    request, initRequest
}